<template>
  <el-dialog
    title="查询语句管理"
    :visible="visible"
    @update:visible="handleClose"
    width="1200px"
    :close-on-click-modal="false"
    custom-class="core-run-dialog-wrapper"
  >
    <div class="core-run-dialog">
      <!-- 数据源选择 -->
      <div class="section">
        <h4>选择指标库</h4>
        <el-select
          v-model="selectedDataSource"
          placeholder="请选择数据源"
          @change="handleDataSourceChange"
          style="width: 100%"
        >
          <el-option
            v-for="item in dataSources"
            :key="item.pkid"
            :label="item.sourceName"
            :value="item.pkid"
          >
            <span>{{ item.sourceName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ item.host }}:{{ item.port }}/{{ item.databaseName }}
            </span>
          </el-option>
        </el-select>
      </div>

      <!-- 表信息展示 -->
      <div class="section" v-if="selectedDataSource">
        <h4>数据源表信息</h4>
        <div class="table-search">
          <el-input
            v-model="tableSearchText"
            placeholder="搜索表名"
            prefix-icon="el-icon-search"
            clearable
            style="width: 300px"
          />
        </div>
        <el-table
          :data="filteredTables"
          height="200"
          stripe
          style="width: 100%; margin-top: 10px"
        >
          <el-table-column prop="tableName" label="表名" min-width="200">
          </el-table-column>
          <el-table-column prop="tableComment" label="表注释" min-width="300">
            <template #default="{ row }">
              {{ row.tableComment || '-' }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- SQL查询 -->
      <div class="section" v-if="selectedDataSource">
        <h4>SQL查询</h4>
        <el-input
          v-model="sqlQuery"
          type="textarea"
          :rows="6"
          placeholder="请输入SQL查询语句"
          style="width: 100%"
        />
        <div class="sql-actions">
          <el-button
            type="primary"
            @click="executeSql"
            :loading="executing"
            :disabled="!sqlQuery.trim()"
          >
            执行
          </el-button>
        </div>
      </div>

      <!-- SQL执行结果 -->
      <div class="section" v-if="queryResults.length > 0">
        <h4>SQL执行结果</h4>
        <el-table
          :data="queryResults"
          stripe
          style="width: 100%"
        >
          <el-table-column
            v-for="column in resultColumns"
            :key="column"
            :prop="column"
            :label="column"
            min-width="150"
            show-overflow-tooltip
          >
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleConfirm"
          :disabled="!sqlQuery.trim() || !selectedDataSource"
          :loading="submitting"
        >
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { Message } from 'element-ui'
import {
  getAllDataSources,
  getDataSourceTables,
  querySQL,
  addCoreRun
} from '@/api/screen-management/indicator-management'

interface DataSource {
  pkid: string
  sourceName: string
  userName: string
  passWord: string
  host: string
  port: number
  databaseName: string
  dbType: string
  remark: string
}

interface TableInfo {
  schemaName: string | null
  tableName: string
  tableComment: string
}

interface Props {
  visible: boolean
  rowData?: any
}

const props = defineProps<Props>()
const emit = defineEmits(['update:visible', 'submit'])

const dataSources = ref<DataSource[]>([])
const selectedDataSource = ref<string>('')
const tables = ref<TableInfo[]>([])
const tableSearchText = ref<string>('')
const sqlQuery = ref<string>('')
const queryResults = ref<any[]>([])
const resultColumns = ref<string[]>([])

const executing = ref<boolean>(false)
const submitting = ref<boolean>(false)

// 过滤后的表格数据
const filteredTables = computed(() => {
  if (!tableSearchText.value) {
    return tables.value
  }
  return tables.value.filter(table =>
    table.tableName.toLowerCase().includes(tableSearchText.value.toLowerCase()) ||
    (table.tableComment && table.tableComment.toLowerCase().includes(tableSearchText.value.toLowerCase()))
  )
})

// 获取数据源列表
const fetchDataSources = async (): Promise<void> => {
  try {
    const response = await getAllDataSources()
    if (response.success) {
      dataSources.value = response.data || []
    }
  } catch (error) {
    console.error('Failed to fetch data sources:', error)
    Message.error('获取数据源失败')
  }
}

// 数据源变化处理
const handleDataSourceChange = async (): Promise<void> => {
  if (!selectedDataSource.value) {
    tables.value = []
    return
  }

  try {
    const response = await getDataSourceTables(selectedDataSource.value)
    if (response.success) {
      tables.value = response.data || []
    }
  } catch (error) {
    console.error('Failed to fetch tables:', error)
    Message.error('获取表信息失败')
  }
}

// 执行SQL
const executeSql = async (): Promise<void> => {
  if (!sqlQuery.value.trim() || !selectedDataSource.value) {
    return
  }

  executing.value = true
  try {
    const response = await querySQL(selectedDataSource.value, sqlQuery.value)
    if (response.success && response.data && response.data.length > 0) {
      queryResults.value = response.data
      // 获取列名
      resultColumns.value = Object.keys(response.data[0])
      Message.success('SQL执行成功')
    } else {
      queryResults.value = []
      resultColumns.value = []
    }
  } catch (error) {
    console.error('Failed to execute SQL:', error)
    Message.error('SQL执行失败')
  } finally {
    executing.value = false
  }
}

// 确定按钮处理
const handleConfirm = async (): Promise<void> => {
  if (!sqlQuery.value.trim() || !selectedDataSource.value || !props.rowData?.pkid) {
    return
  }

  submitting.value = true
  try {
    const data = {
      coreRun: sqlQuery.value,
      coreRunDataSource: selectedDataSource.value,
      indexId: props.rowData.pkid
    }

    const response = await addCoreRun(data)
    if (response.success) {
      Message.success('查询语句保存成功')
      emit('submit', data)
      handleClose()
    }
  } catch (error) {
    console.error('Failed to save core run:', error)
    Message.error('保存失败')
  } finally {
    submitting.value = false
  }
}

// 关闭弹窗
const handleClose = (): void => {
  emit('update:visible', false)
}

// 重置数据
const resetData = (): void => {
  selectedDataSource.value = ''
  tables.value = []
  tableSearchText.value = ''
  sqlQuery.value = ''
  queryResults.value = []
  resultColumns.value = []
}

// 监听弹窗显示状态
watch(() => props.visible, async (newVal) => {
  if (newVal) {
    await fetchDataSources()
    // 如果有现有的数据，填充到对应输入框
    if (props.rowData?.coreRun) {
      sqlQuery.value = props.rowData.coreRun
    }
    if (props.rowData?.coreRunDataSource) {
      selectedDataSource.value = props.rowData.coreRunDataSource
      // 选择数据源后自动加载表信息
      await handleDataSourceChange()
    }
  } else {
    resetData()
  }
})

onMounted(() => {
  if (props.visible) {
    fetchDataSources()
  }
})
</script>

<style scoped lang="scss">
.core-run-dialog {
  max-height: 80vh;
  overflow-y: auto;
  
  .section {
    margin-bottom: 24px;

    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }

    .table-search {
      margin-bottom: 10px;
    }

    .sql-actions {
      margin-top: 12px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.dialog-footer {
  text-align: right;
}

// 数据源选项样式
:deep(.el-select-dropdown__item) {
  height: auto;
  line-height: 1.5;
  padding: 8px 20px;
}

// 弹窗高度限制
:deep(.core-run-dialog-wrapper) {
  .el-dialog {
    max-height: 80vh;
    margin-top: 5vh !important;
    margin-bottom: 5vh !important;
    display: flex;
    flex-direction: column;
  }
  
  .el-dialog__body {
    flex: 1;
    overflow: hidden;
    padding: 20px 20px 0;
  }
  
  .el-dialog__footer {
    flex-shrink: 0;
    padding: 10px 20px 20px;
  }
}
</style> 